'use strict';

const Controller = require('egg').Controller;
const bcrypt = require('bcrypt');
const moment = require('moment');

class UserController extends Controller {
  // 登录接口
  async login() {
    this.ctx.validate({
      phone: 'string',
      code: 'string',
    });
    const { phone, code } = this.ctx.request.body;
    const user = await this.ctx.model.User.find({ where: { phone } });
    if (!user) { // 用户不存在
      this.ctx.message = '用户不存在';
      this.ctx.status = 403;
    }
    if (await bcrypt.compare(code, user.passwordHash)) {
      const { id: userId, role } = user;
      const data = {
        userId,
        role,
        token: this.app.jwt.sign({
          role,
          sub: userId,
        }, this.app.config.jwt.secret),
      };
      switch (role) {
        case 'admin':
          data.nickname = user.phone;
          break;
        case 'merchant':
          data.nickname = user.phone;
          break;
        case 'dietician':
          data.nickname = user.name;
          break;
        case 'member':
          data.nickname = user.nickname;
          break;
        case 'general':
          data.nickname = user.nickname;
          break;
        default:

      }
      this.ctx.body = data;
    } else {
      this.ctx.message = '密码不正确，请重置密码';
      this.ctx.status = 403;
    }
  }
  // 登录app接口
  async loginApp() {
    this.ctx.validate({
      phone: 'string',
      code: 'string',
    });
    const { phone, code } = this.ctx.request.body;
    const store = await this.ctx.model.Store.findOne({ where: { phone } });
    console.log('store', store);
    if (!store) { // 店铺不存在
      this.ctx.message = '用户不存在';
      this.ctx.status = 403;
    }
    if (await this.ctx.model.SmsCode.verify(phone, code) && store.status === 'published') {
      const { id: storeId } = store;
      const data = {
        storeId,
        token: this.app.jwt.sign({
          sub: storeId,
        }, this.app.config.jwt.secret),
      };
      this.ctx.body = data;
    } else {
      this.ctx.message = '密码不正确，请重置密码';
      this.ctx.status = 403;
    }
  }
  // 通过短信验证码登录并设置密码
  async resetAndLoginBySmsCode() {
    this.ctx.validate({
      phone: 'string',
      code: 'string',
    });
    const { phone, code } = this.ctx.request.body;
    if (await this.ctx.model.SmsCode.verify(phone, code)) {
      const phoneUser = await this.ctx.model.Phone.findByPk(phone);
      if (phoneUser) {
        const currentUser = await this.ctx.model.User.findByPk(phoneUser.userId);
        const data = {
          userId: currentUser.id,
          role: currentUser.role,
          token: this.app.jwt.sign({
            role: currentUser.role,
            sub: currentUser.id,
          }, this.app.config.jwt.secret),
        };
        console.log('merchant data', data);
        this.ctx.body = data;
      } else {
        const user = await this.ctx.model.User.create({ role: 'general' });
        await this.ctx.model.Phone.create({ number: phone, userId: user.id });
        const data = {
          userId: user.id,
          role: user.role,
          token: this.app.jwt.sign({
            role: user.role,
            sub: user.id,
          }, this.app.config.jwt.secret),
        };
        console.log('merchant data', data);
        this.ctx.body = data;

      }

    } else {
      this.ctx.message = '验证码错误';
      this.ctx.status = 403;
    }
  }
  // 获取当前用户信息
  async info() {
    const user = await this.ctx.model.User.findById(this.ctx.state.user.sub,
      {
        attributes: [
          'id',
          'nickname',
          'phone',
          'name',
          'imageHash',
          'role',
          'receiverAddress',
          'receiverName',
          'receiverPhone',
          'classifyId',
        ],
        raw: true,
      }
    );
    this.ctx.body = user;
  }
  // 通过小程序获取当前用户信息
  async infoFromWeapp() {
    const { ctx, app } = this;
    const loginService = app.weapp.LoginService.create(ctx.request, ctx.response);
    const { userInfo } = await loginService.check();
    console.log('UserController userInfoFromWeapp userInfo', userInfo);
    const { openId } = userInfo;
    const user = await this.ctx.model.User.findOne({
      include: [{
        model: this.ctx.model.WechatAccount,
        where: { openId },
      }],
    });
    ctx.body = {
      userInfo,
      user,
      bound: !!user,
    };
  }
  // 通过短信验证码绑定账号
  async bindPhoneBySmsCode() {
    this.ctx.validate({
      phone: 'string',
      code: 'string',
    });
    const { phone, code } = this.ctx.request.body;
    if (await this.ctx.model.SmsCode.verify(phone, code)) {
      const { ctx, app } = this;
      const loginService = app.weapp.LoginService.create(ctx.request, ctx.response);
      const data = await loginService.check();
      console.log('UserController bindPhoneBySmsCode data', data);
      const { openId, nickName: nickname } = data.userInfo;
      const defaults = { phone, nickname };
      const [ user ] = await this.ctx.model.User.findOrCreate({
        defaults,
        where: { phone },
      });
      const [ wechatAccount ] = await this.ctx.model.WechatAccount.findOrCreate({
        defaults: { openId },
        where: { openId },
      });
      await wechatAccount.update({ userId: user.id });
      this.ctx.status = 204;
    } else {
      this.ctx.message = '验证码错误';
      this.ctx.status = 403;
    }
  }
  async loginFromWeapp() {
    console.log('loginFromWeapploginFromWeapploginFromWeapp');
    const { ctx, app } = this;
    const { inviterId } = ctx.request.query;
    console.log('loginFromWeapploginFromWeapploginFromWeapp ctx', ctx);
    const loginService = app.weapp.LoginService.create(ctx.request, ctx.response);
    const data = await loginService.login();
    const { openId, nickName: nickname, avatarUrl } = data.userInfo;
    console.log('loginFromWeapploginFromWeapploginFromWeapp openId', openId);
    console.log('loginFromWeapploginFromWeapploginFromWeapp avatarUrl', avatarUrl);
    const [ wechatAccount ] = await this.ctx.model.WechatAccount.findOrCreate({
      defaults: { openId, avatarUrl },
      where: { openId },
    });
    console.log('loginFromWeapp wechatAccount.userId', wechatAccount.userId);
    if (wechatAccount.userId) {
      const currentUser = await this.ctx.model.User.findByPk(wechatAccount.userId);
      if (!currentUser.inviterId) {
        await currentUser.update({ inviterId });
      }
    }
    if (wechatAccount && !wechatAccount.userId) {
      console.log('wechatAccount && !wechatAccount.userId');
      const defaults = { nickname, role: 'general', inviterId };
      console.log('wechatAccount && !wechatAccount.userId defaults', defaults);
      const user = await this.ctx.model.User.create(defaults);
      console.log('wechatAccount && !wechatAccount.userId user', user);
      await wechatAccount.update({ userId: user.id });
    }
    ctx.body = data;
  }
  // 请求发送验证码 trove
  async smsCode() {
    this.ctx.validate({ phone: 'string' });
    await this.ctx.model.SmsCode.send(this.ctx.request.body.phone);
    this.ctx.status = 204;
  }
  // 用户信息记录
  async record() {
    this.ctx.validate({
      name: { type: 'string', required: false },
      nickname: { type: 'string', required: false },
      imageHash: { type: 'string', required: false },
      receiverAddress: { type: 'string', required: false },
      receiverName: { type: 'string', required: false },
      receiverPhone: { type: 'string', required: false },
    });
    const user = await this.ctx.model.User.findById(this.ctx.state.user.sub);
    const { name, nickname, imageHash, receiverAddress, receiverName, receiverPhone } = this.ctx.request.body;
    const data = {};
    if (name) data.name = name;
    if (nickname) data.nickname = nickname;
    if (receiverAddress) data.receiverAddress = receiverAddress;
    if (receiverName) data.receiverName = receiverName;
    if (receiverPhone) data.receiverPhone = receiverPhone;
    if (imageHash) {
      await this.ctx.service.file.record('image', imageHash);
      data.fileHash = imageHash;
    }
    await user.update(data);
  }
  // 收藏功能
  async follow() {
    console.log('follow');
    const { ctx, app } = this;
    this.ctx.validate({
      storeId: { type: 'int' },
    });
    const store = await this.ctx.model.Store.findByPK(this.ctx.request.body.storeId);
    console.log('await this.ctx.model.Store.findById store', store);
    if (store) {
      const loginService = app.weapp.LoginService.create(ctx.request, ctx.response);
      const { userInfo } = await loginService.check();
      console.log('UserController userInfoFromWeapp userInfo', userInfo);
      const { openId } = userInfo;
      const weappUser = await this.ctx.model.WechatAccount.findByPk(openId);
      const { userId } = weappUser;
      const user = await this.ctx.model.User.findByPk(userId);
      console.log('await this.ctx.model.Store.findById user', user);
      await store.addUser(user);
      this.ctx.status = 204;
    } else {
      this.ctx.status = 403;
    }
  }
  // 测试
  async test() {
    await this.ctx.render('verify.njk');
  }
  // 测试
  async open() {
    console.log('12321312312312');
  }
  // 测试
  async invite() {
    await this.ctx.render('invite.njk');
  }
  // 查看团队佣金日志
  async teamViewLog() {
    const user = await this.ctx.model.User.findByPk(this.ctx.state.user.sub);
    console.log('teamViewLog user', user);
    const { id: userId, role } = user;
    const options = {
      where: { userId },
    };
    switch (role) {
      case 'admin':
        this.ctx.body = '会员用户';
        break;
      case 'higher': {
        const groupCommissionLog = await this.ctx.model.GroupCommissionLog.findAll(options);
        this.ctx.body = groupCommissionLog;
      }
        break;
      case 'facilitator': {
        const groupCommissionLog = await this.ctx.model.GroupCommissionLog.findAll(options);
        this.ctx.body = groupCommissionLog;
      }
        break;
      default:
    }
  }
  // 查看佣金记录
  async viewLog() {
    const user = await this.ctx.model.User.findById(this.ctx.state.user.sub);
    const { id: userId, role } = user;
    const { query } = this.ctx.request;
    let pageSize = 10;
    if (query.pageSize) pageSize = Number(query.pageSize);
    const where = {};
    if (userId) where.userId = userId;
    const options = {
      limit: pageSize,
      offset: query.currentPage ? pageSize * (query.currentPage - 1) : 0,
      where,
    };
    console.log('model.Store.findAndCountAll options', options);
    const { count: total, rows: list } = await this.ctx.model.BalanceRecord.findAndCountAll(
      options
    );
    switch (role) {
      case 'admin':
        this.ctx.body = '会员用户';
        break;
      case 'facilitator':
        this.ctx.body = {
          list,
          pagination: {
            total,
            pageSize,
            current: parseInt(query.currentPage, 10) || 1,
          },
        };
        break;
      case 'higher':
        this.ctx.body = {
          list,
          pagination: {
            total,
            pageSize,
            current: parseInt(query.currentPage, 10) || 1,
          },
        };
        break;
      default:
    }
  }
  // 获取首页数据
  async homePage() {
    const { ctx } = this;
    console.log('ctx.state.user.sub', ctx.state.user.sub);
    const currentUser = await ctx.model.User.findByPk(ctx.state.user.sub);
    console.log('homePagehomePagehomePage', currentUser);
    if (currentUser.role === 'admin') {
      const pageSize = 10;
      const status = 'completed';
      const createdAt = {
        [this.ctx.model.Op.between]: [ moment().startOf('day').format('YYYYMMDD'), moment().endOf('day').format('YYYYMMDD') ],
      };
      const userOptions = { where: { createdAt } };
      const newOrdersOptions = {
        limit: pageSize,
        where: { createdAt },
      };
      const newOrders = await this.ctx.model.Order.findAll(newOrdersOptions);// 查找所有新用户
      const newUsers = await this.ctx.model.User.findAll(userOptions);// 查找所有新用户
      const allNewUsers = newUsers.map(user => (user.id));// 取出所有id
      const newOptions = { where: { createdAt, status } };
      const allNewOrder = await this.ctx.model.Order.findAll(newOptions);// 查找所有已完成新订单
      const allNewOrderPrice = allNewOrder.map(order => (order.price));// 取出所有新订单金额
      let allNewPrice = 0;
      for (let i = allNewOrderPrice.length - 1; i >= 0; i--) {
        allNewPrice += allNewOrderPrice[i];
      }
      const options = { where: { status } };
      const allOrder = await this.ctx.model.Order.findAll(options);// 查找所有已完成订单
      const allOrderPrice = allOrder.map(order => (order.price));// 取出所有订单金额
      let allPrice = 0;
      for (let i = allOrderPrice.length - 1; i >= 0; i--) {
        allPrice += allOrderPrice[i];
      }
      const users = await this.ctx.model.User.findAll({ raw: true });// 查找所有用户
      const alluser = users.map(user => (user.id));// 取出所有用户Id
      const storeOptions = {
        limit: pageSize,
        order: [
          [ 'oveRall', 'DESC' ],
        ],
      };
      const stores = await this.ctx.model.Store.findAll(storeOptions);// 店铺排行
      const storeClass = await this.ctx.model.StoreClass.findAll(storeOptions);// 店铺所有分类
      // 所有交易金额 最新交易额  支付笔数 最新支付笔数 所有用户 最新用户 最新订单 店铺排行 分类排行
      const data = {
        allPrice,
        allNewPrice,
        amount: allOrderPrice.length,
        newAmount: allNewOrderPrice.length,
        alluser: alluser.length,
        allNewUsers: allNewUsers.length,
        newOrders,
        stores,
        storeClass,
      };
      this.ctx.body = data;
    }
    if (currentUser.role === 'facilitator') {
      const status = 'completed';
      const pageSize = 10;
      const createdAt = {
        [this.ctx.model.Op.between]: [ moment().startOf('day').format('YYYYMMDD'), moment().endOf('day').format('YYYYMMDD') ],
      };
      const newOptions = { where: { createdAt, status } };
      const allNewOrder = await this.ctx.model.Order.findAll(newOptions);
      console.log('allNewOrder', allNewOrder);
      const storeOptions = {
        limit: pageSize,
        where: { facilitatorId: currentUser.id },
        order: [
          [ 'oveRall', 'DESC' ],
        ],
      };
      console.log('storeOptions', storeOptions);
      const stores = await this.ctx.model.Store.findAll(storeOptions);// 店铺排行
      const allPrice = {
        where: { facilitatorId: currentUser.id },
      };
      const storesPrice = await this.ctx.model.Store.findAll(allPrice);// 店铺排行
      const allNewOrderPrice = storesPrice.map(ove => (ove.oveRall));// 取出所有新订单金额
      let allstorePrice = 0;
      for (let i = allNewOrderPrice.length - 1; i >= 0; i--) {
        allstorePrice += allNewOrderPrice[i];
      }
      const teamUser = await this.ctx.model.User.findAll({ where: { inviterId: currentUser.id }, raw: true });
      const data = { allNewOrder, allstorePrice, stores, teamUser: teamUser.length };
      this.ctx.body = data;
    }
  }
  // 商户首页数据
  async appHomePage() {
    const { ctx } = this;
    console.log('ctx.state.user.sub', ctx.state.user.sub);
    const currentStore = await ctx.model.Store.findOne({ where: { userId: ctx.state.user.sub } });
    console.log('store', currentStore);
    if (currentStore) {
      const status = 'completed';
      const createdAt = {
        [this.ctx.model.Op.between]: [ moment().startOf('day').format('YYYYMMDD'), moment().endOf('day').format('YYYYMMDD') ],
      };
      const ordersOptions = {
        where: {
          storeId: currentStore.id,
          status,
        },
      };
      const allOrders = await this.ctx.model.Order.findAll(ordersOptions);// 查找所有已完成订单
      const allOrderPrice = allOrders.map(order => (order.price));// 取出所有已完成订单的金额
      let allPrice = 0;
      for (let i = allOrderPrice.length - 1; i >= 0; i--) {
        allPrice += allOrderPrice[i];
      }// 得到所有已完成订单的金额 allPrice
      const newOrdersOptions = {
        where: {
          createdAt,
          status,
          storeId: currentStore.id,
        },
      };
      const allNewOrder = await this.ctx.model.Order.findAll(newOrdersOptions);// 查找所有已完成新订单
      const allNewOrderPrice = allNewOrder.map(order => (order.price));// 取出所有新订单金额
      let allNewPrice = 0;
      for (let i = allNewOrderPrice.length - 1; i >= 0; i--) {
        allNewPrice += allNewOrderPrice[i];
      }
      // 总交易金额 新交易额  总订单数 最新订单数
      const data = {
        allPrice,
        allNewPrice,
        amount: allOrderPrice.length,
        newAmount: allNewOrderPrice.length,
      };
      this.ctx.body = data;
    }
  }

  // 测试
  async sendDatasss() {
    const sendData = {
      phone: '15255223063',
      nickname: 'FＦＦＦＦＦ',
      TemplateCode: 'SMS_158492778',
    };
    console.log('会员锁粉 bindInviterFromWeapp sendData', sendData);
    await this.ctx.service.smsCode.send(sendData);
  }
}

module.exports = UserController;
